﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorldServer.Data;
using AionCxxLibrary.Utilities;
using AionCxxLibrary.Enums;
using WorldServer.DAO;
using WorldServer.Data.Templates;

namespace WorldServer.Models
{
    /// <summary>
    /// This class represents an Item.
    /// It should be used only to instanciate real AION items.
    /// Do not create a new Item() to hold item data. Use a TItem (or TItemEx) instead (TemplateItem or TemplateItemExtended)
    /// </summary>
    public class Item : IAionIDAwareObject
    {
        public static byte OptionalSocket_None = 0;
        public static byte OptionalSocket_PrimaryItem = 1;
        public static byte OptionalSocket_FusionedItem = 2;
        public static byte OptionalSocket_All = (byte)(OptionalSocket_PrimaryItem | OptionalSocket_FusionedItem);

        public readonly long InternalID;
        public readonly int TemplateID;
        public long Count = 1;
        public int Color = 0;
        public string Crafter = "";
        public long CreationTime = 0;
        public int TemporaryTradeTimeLeft = 0;
        public bool SoulBound;
        public byte EnchantLevel;
        public int SkinID;
        public Item FusionedItem;
        public byte OptionalSocketFlag;
        public bool Equipped;

        public readonly ItemTemplate Template;

        public int Slot;

        private int AionID;

        public Item(long internalId, int templateId)
        {
            InternalID = internalId;
            TemplateID = templateId;
            Template = Datastore.ItemsById[templateId];
            AionID = GUIDManager.NextID();
        }

        public Item(long internalId, int templateId, long count)
        {
            InternalID = internalId;
            TemplateID = templateId;
            Count = count;
        }

        public int GetGUID() { return AionID; }

    }

    /// <summary>
    /// This class represents a character storage.
    /// Like for items, must be used only to represent a living storage.
    /// Use TStorage for templating/storing data.
    /// </summary>
    public class Storage : EventAwareList<Item>
    {
        public readonly StorageType storageType;
        public readonly Character Character;

        public readonly short Size;

        public bool Full
        {
            get
            {
                return (Count - (storageType == StorageType.Cube ? FindAll(i => i.Equipped).Count + 1 : 0)) >= Size;
            }
        }

        public Storage(StorageType type, Character character)
        {
            storageType = type;
            Character = character;
            // Initialize Storage Size
            if (type == StorageType.Cube) { Size = ItemDAO.SelectCubeSize(character.GetGUID()); }
            else if (type == StorageType.AccountWarehouse) { Size = 18; }
            else if (type == StorageType.Broker) { Size = 15; }
            else if (type == StorageType.LegionWarehouse) { Size = 49; }
            else if (type == StorageType.Mailbox) { Size = 100; }
            else if (type == StorageType.PetBag6Slot) { Size = 6; }
            else if (type == StorageType.PetBag12Slot) { Size = 12; }
            else if (type == StorageType.PetBag18Slot) { Size = 18; }
            else if (type == StorageType.PetBag24Slot) { Size = 24; }
            else if (type == StorageType.Warehouse) { Size = ItemDAO.SelectCharacterWarehouseSize(character.GetGUID()); }
            else
                Log.Error("Cannot determine storage size for StorageType." + type.ToString());
            // load storage contents from database
            AddRange(ItemDAO.SelectStorageByCharacterId(character.GetGUID(), (byte)(int)type));
            OnAdd += new EventAwareListAddEvent<Item>(Storage_OnAdd);
            OnRemove += new EventAwareListRemoveEvent<Item>(Storage_OnRemove);
            BeforeAdd += new EventAwareListBeforeAddEvent<Item>(Storage_BeforeAdd);
        }

        bool Storage_BeforeAdd(object sender, EventArgs<Item> e)
        {
            if (Count >= Size)
            {
                return false;
            }
            return true;
        }

        void Storage_OnRemove(object sender, EventArgs<Item> e)
        {
            ItemDAO.DeleteFromStorage(e.Value.InternalID, (byte)(int)storageType);
        }

        void Storage_OnAdd(object sender, EventArgs<Item> e)
        {
            ItemDAO.InsertToStorage(e.Value.InternalID, Character.GetGUID(), (byte)(int)storageType, e.Value.Slot);
        }

        public int LookupSlotFor(int itemId, long count)
        {
            // 1. Try to find an existing item in storage.
            Item existingItem = Find(it => !it.Equipped && it.TemplateID == itemId);
            if (existingItem != null && (existingItem.Count + count) <= existingItem.Template.MaxStackCount)
                return existingItem.Slot;
            // 2. If none, seek a free slot
            for (int i = 0; i < Size; i++)
            {
                Item item = Find(it => !it.Equipped && it.Slot == i);
                if (item == null || (item.Template.ID == 182400001 && Find(it => it.Slot == 0 && it.Template.ID != 182400001) == null))
                    return i;
            }
            return 0xFFFF;
        }

    }
}
